package org.lw.springbootlw.web.controller;

import org.lw.springbootlw.common.response.ApiResponse;
import org.lw.springbootlw.common.response.LoginRequest;
import org.lw.springbootlw.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/web/auth")
public class WebAuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtUtil jwtUtil; // 用于生成 JWT


    @PostMapping("/login")
    public ResponseEntity<ApiResponse<String>> login(@RequestBody LoginRequest loginRequest) throws BadCredentialsException, Exception {
        // 参数检查
        if (loginRequest.getUsername() == null || loginRequest.getPassword() == null ||
                loginRequest.getUsername().isEmpty() || loginRequest.getPassword().isEmpty()) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(400, "用户名和密码不能为空", null));
        }

        System.out.println("Attempting login with username: " + loginRequest.getUsername()+ " and password: " + loginRequest.getPassword());
        // 调用 Spring Security 的认证方法
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
            );

        System.out.println("Authentication successful: " + authentication);
        // 登录成功，生成 JWT
        UserDetails userDetails = userDetailsService.loadUserByUsername(loginRequest.getUsername());
        String jwt = jwtUtil.generateToken(userDetails.getUsername());
        return ResponseEntity.ok().body(new ApiResponse<>(200, "登录成功", jwt)); // 返回 JWT

    }


}

